<?php

namespace Aoe\Util\Logger;

use Closure;

/**
 * # 日志
 */
class Logger
{
    const int DEBUG = 2;
    const int ERROR = 1;
    const int ALL   = 3;
    
    /**
     * @var Record[] 保存所有的日志信息
     * @noinspection PhpGetterAndSetterCanBeReplacedWithPropertyHooksInspection
     */
    protected array $records = [];

    /**
     * @var ?Closure 翻译器
     */
    protected ?Closure $translator = null;
    
    /**
     * ## 生成记录
     *
     * @param string $name    记录器名
     * @param int    $level   错误等级
     * @param string $message 错误信息
     * @param array  $context 错误信息参数
     * @param int    $back    调用堆栈回退次数
     *
     * @return string
     */
    public function insert(string $name, int $level, string $message, array $context = [], int $back = 1): string
    {
        $traces = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, $back + 1);

        $str = $this->_translate($message, $context);

        $this->records[] = new Record([
            Record::MESSAGE => $str,
            Record::LEVEL   => $level,
            Record::NAME    => $name,
            Record::FILE    => basename($traces[$back]['file']),
            Record::LINE    => $traces[$back]['line'],
        ]);
        return $str;
    }
    
    private function _translate(string $message, $context = []): string
    {
        return ($this->translator) ? ($this->translator)($message, $context) : message($message, $context);
    }

    /**
     * 获取全部标记信息
     *
     * @return array
     */
    public function getRecords(): array
    {
        return $this->records;
    }

    public function setTranslator(Closure $translator): void
    {
        $this->translator = $translator;
    }
}